package com.leenleda.ips.widget;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.os.Build;
import android.os.Looper;
import android.os.Message;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.leenleda.ips.BaseActivity;
import com.leenleda.ips.R;
import com.leenleda.ips.util.LogUtils;
import com.leenleda.ips.util.Utils;

public class PopLayout implements View.OnTouchListener {

    private Context mContext;
    private WindowManager wm;
    private LinearLayout linearLayout;
    private int screenWidth = 0;


    public PopLayout(Context context, int width) {
        mContext = context;
        if (width != 0)
            screenWidth = width / 3;
        LogUtils.e("SLKDNVLDS", "====screenWidth=======" + screenWidth);
    }

    private android.os.Handler mHandler = new android.os.Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            LogUtils.e("SLKDNVDLDS", "====333333===" + Utils.getSetTime() / 1000);
//            long currentTime = Utils.getSetTime();
            long time = Utils.getSetTime() / 1000 - duringTime;
            if (time > -1 && time < 1) {
                LogUtils.e("SLKDNVDLDS", "====duringTime===" + duringTime);
                missView();
            }
//            animDismiss();
        }
    };

    private void missView() {
        LogUtils.e("SLKDNVLDS", "====missView=======");
        if (null != linearLayout && null != linearLayout.getParent()) {
            if (childView != null && childView instanceof MarqueeView) {
                ((MarqueeView) childView).stopScroll();
                LogUtils.e("SLKDNVLDS", "====stopScroll=======");
            }
            wm.removeView(linearLayout);
        }
        childView = null;
        linearLayout = null;
        isShow = false;
    }

    private boolean isShow = false;
    private long duringTime = 0;

    //end right 从尾开始滚动 右->左  1, start left 从头开始滚动 左->右  0
    public void show(boolean fixed, String content, int strColor, int textSize, boolean rollType, long time, int speed, int strBack, int gravity) {

//        ILog.e("SLKDNVLDS", "====show=======" + isShow);


        duringTime = Utils.getSetTime() / 1000 + time;
//        ILog.e("SLKDNVLDSA", "====time=======" + time);
//        ILog.e("SLKDNVLDSA", "====duringTime=======" + duringTime);
//        ILog.e("SLKDNVLDSA", "====getSetTime===" + Utils.getSetTime() / 1000);
        if (isShow) {
            return;
        }
        isShow = true;

        if (fixed)
            addFixView(content, strColor, textSize);
        else
            addMarqueeView(content, strColor, speed, textSize, rollType ? 1 : 0);
        createView(gravity, strBack);

//        if (fixed)
//            animShow();
        mHandler.sendEmptyMessageDelayed(20, time * 1000);
    }

    /**
     * 向外部暴露关闭的方法
     */
    public boolean dismiss(boolean close) {
//        ILog.e("SLKDNVLDSA", "=-----===close=======" + close);
        if (!close) {
            long cur = Utils.getSetTime() / 1000;
//            ILog.e("SLKDNVLDSA", "=-----===cur=======" + cur);
//            ILog.e("SLKDNVLDSA", "=-----===dur=======" + duringTime);
            if (cur < duringTime)
                return false;
        }
        missView();
        return true;
    }

    /**
     * 添加滚动view
     */
    private void addMarqueeView(String content, int strColor, int speed, int size, int showFrom) {
        childView = View.inflate(mContext, R.layout.pop_marquee, null);//这里是你弹窗的UI

        ((MarqueeView) childView).setTextColor(strColor);
        ((MarqueeView) childView).setTextSize(size);
        ((MarqueeView) childView).setViewFrom(showFrom);
        ((MarqueeView) childView).setTextSpeed(speed);
        ((MarqueeView) childView).setText(content);
        ((MarqueeView) childView).startScroll();

        WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        params.height = Utils.dip2px(mContext, 83);

        Display display = BaseActivity.getForegroundActivity().getWindowManager().getDefaultDisplay();
//        int width = display.getWidth() * 2 / 3;
        int width = display.getWidth();
        params.width = width;
        childView.setLayoutParams(params);
    }

    /**
     * 添加固定view
     */
    private void addFixView(String content, int strColor, int size) {
        childView = View.inflate(mContext, R.layout.pop_text, null);//这里是你弹窗的UI

        ((TextView) childView).setTextColor(strColor);
        ((TextView) childView).setTextSize(size);
        ((TextView) childView).setText(content);

        WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        params.height = Utils.dip2px(mContext, 83);
        params.width = LinearLayout.LayoutParams.WRAP_CONTENT;
        childView.setLayoutParams(params);
    }

    private View childView;

    private void createView(int gravity, int strBack) { //准备Window要添加的View
        linearLayout = new LinearLayout(mContext);
        final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        linearLayout.setLayoutParams(layoutParams);
        linearLayout.setOnTouchListener(this);
//        linearLayout.setHorizontalGravity(Gravity.CENTER_HORIZONTAL);
        linearLayout.setGravity(Gravity.CENTER_HORIZONTAL);
        linearLayout.setBackgroundColor(strBack);
        linearLayout.addView(childView);

        // 定义WindowManager 并且将View添加到WindowManager中去
        wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        WindowManager.LayoutParams wm_params = new WindowManager.LayoutParams();
        wm_params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
        //这里需要注意，因为不同系统版本策略不一，所以需要根据版本判断设置type，否则会引起崩溃。
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) { //大于android SDK 7.1.1
            wm_params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            wm_params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }

        int pos = Gravity.BOTTOM;
        switch (gravity){
            case 1:
                pos = Gravity.TOP;
                break;
            case 2:
                pos = Gravity.CENTER_VERTICAL;
                break;
            default:
            case 3:
                pos = Gravity.BOTTOM;
                break;
        }
        wm_params.gravity = pos;
        wm_params.x = 0;
        wm_params.y = 0;
        wm_params.format = -3;
        // 会影响Toast中的布局消失的时候父控件和子控件消失的时机不一致，比如设置为-1之后就会不同步
        wm_params.alpha = 1f;
        linearLayout.measure(0, 0);
        wm_params.height = Utils.dip2px(mContext, 83);
        wm_params.width = LinearLayout.LayoutParams.MATCH_PARENT;
        wm.addView(linearLayout, wm_params);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return false;
    }


    /**
     * 动画关闭
     */
    private void animDismiss() {
        isShow = false;
        if (linearLayout == null || linearLayout.getParent() == null) {
            return;
        }

        ObjectAnimator animator1 = ObjectAnimator.ofFloat(childView, "alpha", 1, 0);
        ObjectAnimator animator2 = ObjectAnimator.ofFloat(childView, "translationX", 0, -childView.getWidth());

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(animator1, animator2);
        animatorSet.setDuration(4000);
        animatorSet.start();
        animatorSet.addListener(new AnimatorListenerAdapter() {
        });

        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationCancel(Animator animation) {
                super.onAnimationCancel(animation);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation); //移除HeaderToast  (一定要在动画结束的时候移除,不然下次进来的时候由于wm里边已经有控件了，所以会导致卡死)
                if (null != linearLayout && null != linearLayout.getParent()) {
                    if (childView != null) {
                        if (childView instanceof MarqueeView) {
                            ((MarqueeView) childView).stopScroll();
                            LogUtils.e("SLKDNVLDS", "====stopScroll=======");
                        }
                        childView = null;
                    }
                    wm.removeView(linearLayout);
                }
            }
        });
    }

    /**
     * 动画开始
     */
    private void animShow() {
        ObjectAnimator animator1 = ObjectAnimator.ofFloat(childView, "alpha", 0, 1);
        ObjectAnimator animator2 = ObjectAnimator.ofFloat(childView, "translationX", childView.getWidth(), 0);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(animator1, animator2);
        animatorSet.setDuration(4000);
        animatorSet.start();
    }

}
